import os
import logging 
from ffmpy import FFmpeg
import random
import string
import json

logger = logging.getLogger(__name__)

class Trans(object):

    # TODO GPU加速
    
    def __init__(self,target_path='d:/m3u8/hls'):
        self.target_path = target_path


    # 获取文件名和文件路径
    def getFileNameAndPath(self,path):
        index = path.rindex("/") #从右边开始取第一个并返回索引位置
        return path[index:],path[0:index]

    # 视频先转换成h264编码格式
    def trans_video_h264(self,video_path):
        video_name,video_path2 = self.getFileNameAndPath(video_path)
        print(f'video_name:{video_name}, video_path:{video_path2}')

        print(self.target_path+video_name[0:-4])

        if not os.path.exists(self.target_path+video_name[0:-4]):
            os.makedirs(self.target_path+video_name[0:-4])

        ff = FFmpeg(
            executable='D:/Tools/ffmpeg/bin/ffmpeg.exe',
            inputs={video_path:'-hwaccel cuvid -c:v h264_cuvid'},
            outputs={self.target_path+video_name[0:-4]+video_name:' -strict -2 -c:v h264_nvenc'}
        )
        print(ff.cmd)
        ff.run()
        return self.target_path+video_name[0:-4]+video_name

    # 复制成一个大的TS文件
    def copy2ts(self,video_path):
        ts_path = video_path.replace('.mp4','.ts')
        ff = FFmpeg(
            executable='D:/Tools/ffmpeg/bin/ffmpeg.exe',
            inputs={video_path:None},
            outputs={ts_path:'-c copy'}
        )
        print(ff.cmd)
        try:
            ff.run()
        except Exception as e:
            pass
        if os.path.exists(video_path):
            os.remove(video_path)
        return ts_path

    # 先判断是否可以直接切片，转换太慢 视频切片 输出索引和小ts文件，返回索引名和需要切片的ts路径
    def cut_ts_video(self,ts_path):

        ts_name,ts_prefix_path = self.getFileNameAndPath(ts_path)

        m3u8_path = self.target_path+ts_name[0:-3]+ts_name[0:-3]+".m3u8"
        cut_m3u8_path = self.target_path+ts_name[0:-3]+ts_name[0:-3]

        ff = FFmpeg(
            executable='D:/Tools/ffmpeg/bin/ffmpeg.exe',
            inputs={ts_path:None},
            outputs={None:'-c copy -map 0 -y -f segment -segment_list {0} -segment_time 60 -bsf:v h264_mp4toannexb {1}%03d.ts'.format(m3u8_path,cut_m3u8_path)}
        )
        print(ff.cmd)
        try:
            ff.run()

        except Exception as e:
            pass
        return ts_name,ts_path

    # 输出视频截图 作为封面 还会报错
    def output_img(self,ts_path):
        ts_name,ts_prefix_path = self.getFileNameAndPath(ts_path)
        out_path_img = self.target_path + ts_name[0:-3]+ts_name[0:-3] + '.jpg'
        ff = FFmpeg(
            executable='D:/Tools/ffmpeg/bin/ffmpeg.exe',
            inputs={ts_path:None},
            outputs={
                out_path_img:'-y -ss 60 -f image2 -frames:v 1'
            }
        )
        print(ff.cmd)
        try:
            ff.run()
        except Exception as e:
            pass
        if os.path.exists(ts_path):
            os.remove(ts_path)

    # 将生成的文件ts路径记录
    def write_path(self,ts_path):
        fb = open('d:/m3u8/videoData.txt','a')
        fb.write(ts_path+'\n')
        fb.close()

    # 根据生成的ts文件路径 转换出 json
    def write_relations_json(self,file_path):
        list_data=[]
        filePaths=open(file_path,'r')
        for line in filePaths:
            print(line)
            ts_name,ts_prefix_path = self.getFileNameAndPath(line.strip('\n'))
            data = {
              'videoName': ts_name[1:-3],
              'videoPath': ts_name[0:-3]+ts_name.replace('ts', 'm3u8'),
              'videoImg': ts_name[0:-3]+ts_name.replace('ts', 'jpg')
            }
            print(data)
            list_data.append(data)

        content = json.dumps(list_data,ensure_ascii=False)
        fb = open('d:/m3u8/videoData.json','a')
        fb.write(content+'\n')
        fb.close()

    # 可以换递归获取文件
    def find_all_file(self,path):
        for root ,ds ,fs in os.walk(path):
            # for d in ds:
            #     print(d)
            for f in fs:
                if f.endswith('.mp4'):
                    fullname = os.path.join(root,f)
                    print(fullname)
                    yield fullname.replace('\\', '/')



if __name__ == '__main__':
    trans = Trans()

    # for path in trans.find_all_file('F:/'):
    #     new_video_path = trans.trans_video_h264(path)
    #     ts_path = trans.copy2ts(new_video_path)
    #     trans.cut_ts_video(ts_path)
    #     trans.output_img(ts_path)
    #     trans.write_path(ts_path)

    # trans.write_relations_json('D:/m3u8/videoData.txt')

